

import request from '@/api/request.js'
import config from '@/config'
//   获取上传凭证  
export const get_upload_token = ()=>{
	return request.get('/upload/token')
}
//  上传到七牛
export const uploadQN = (params)=>{
	return request.post('https://upload-z1.qiniup.com',params)
}


export const createFileName = (type)=> {
        let _name = Math.random().toString(16).slice(2);
        _name += +new Date();
        if (type) {
        return _name + "." + type;
        }
        return _name;
  }

export const uploadFile = async (file)=>{
    let result  =null; 
    try {
        let { token } = await get_upload_token(); //  去服务器获取上传凭证 

        let type = file.type.split("/")[1];
        let key = createFileName(type);
    
            let formdata = new FormData();
            formdata.append("file", file);
            formdata.append("key", key);
            formdata.append("token", token);
    
            result = await uploadQN(formdata);
    } catch (error) {
         return Promise.reject(error)
    }

       return  config.baseImgUrl+result.key
}